package com.topmap.controller;

import com.topmap.controller.viewobject.ArticleVO;
import com.topmap.dao.ArticleDOMapper;
import com.topmap.error.BusinessException;
import com.topmap.response.CommonReturnType;
import com.topmap.service.ArticleService;
import com.topmap.service.model.ArticleModel;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: MaHuadong
 * @Date: 2019/7/18 13:27
 * @Version 1.0
 */
@Controller("/article")
@RequestMapping("/article")
//允许跨域
@CrossOrigin(allowCredentials = "true",allowedHeaders = "*")
public class ArticleController extends BaseController {

    @Autowired
    private ArticleService articleService;


    @Autowired
    private ArticleDOMapper articleDOMapper;




    //用户发帖
    @RequestMapping(value = "/postArticle",method = {RequestMethod.POST},consumes={CONTENT_TYPE_FORMED})
    @ResponseBody
    //需要参数：标题，类型，内容，时间
    public CommonReturnType postArticle(@RequestParam(name = "title") String title,
                                     @RequestParam(name = "type") String type,
                                     @RequestParam(name = "content") String content
    ) throws BusinessException, UnsupportedEncodingException, NoSuchAlgorithmException {
        //开始发表文章，需要一个service去执行注册流程
        ArticleModel articleModel =new ArticleModel();

        articleModel.setTitle(title);
        articleModel.setType(type);
        articleModel.setContent(content);
        articleModel.setTime(DateTime.now().toDate());

        articleService.postArticle(articleModel);

        return CommonReturnType.creat(null);

    }


    //获取所有的帖子文章
    @RequestMapping(value = "/listArticle",method = {RequestMethod.GET})
    @ResponseBody
    public CommonReturnType getAllFeiyi(){
        List<ArticleModel> articleModelList=articleService.listArticle();

        //把model转换为供前端展示的vo(涉及到list类型数据的转换)还是使用java8的stream的api
        List<ArticleVO> articleVOList=articleModelList.stream().map(articleModel -> {
            ArticleVO articleVO=this.convertVOFromModel(articleModel);
            return articleVO;
            //转换为list类型，使得可以返回list类型的数据
        }).collect(Collectors.toList());

        //最后将返回给前端的productvo返回给前端
        return CommonReturnType.creat(articleVOList);
    }


    //将model转换为VO返回给前端展示
    private ArticleVO convertVOFromModel(ArticleModel articleModel) {
        if (articleModel==null){
            return null;
        }

        ArticleVO articleVO=new ArticleVO();

        //copy
        BeanUtils.copyProperties(articleModel,articleVO);

        return articleVO;
    }


}
